from selenium import webdriver
from selenium.webdriver.chrome.options import Options
import time
import json
import random

import configparser
cp = configparser.ConfigParser()
cp.read('account.cfg')


def login(username, password):
    chrome_options = Options()
    url = "https://index.baidu.com/#/"
    driver = webdriver.Chrome(chrome_options=chrome_options)
    driver.get(url)
    # driver.implicitly_wait(5)
    # driver.find_element_by_xpath('//*[@id="home"]/div[1]/div[2]/div[1]/div[4]/span').click()
    # driver.implicitly_wait(5)
    # username_input = driver.find_element_by_xpath("//input[@name='userName']")
    # password_input = driver.find_element_by_xpath("//input[@name='password']")
    # username_input.clear()
    # password_input.clear()
    # username_input.send_keys(username)
    # password_input.send_keys(password)
    # driver.find_element_by_xpath("//input[@value='登录']").click()
    # time.sleep(3)
    
    # driver.find_element_by_xpath("//input[@id='TANGRAM__14__button_send_mobile']").click()
    
    time.sleep(30)
    cookies_list = driver.get_cookies()
    # print(cookies_list)
    driver.close()
    return cookies_list


def get_cookies():
    with open('baidu_cookies.txt', encoding="utf-8") as f:
        items = f.read().split('\n')
    all_cookies = []
    for item in items:
        if item != '':
            cookies = {}
            cookies_list = json.loads(item)
            for item in cookies_list:
                cookies[item['name']] = item['value']
            all_cookies.append(cookies)
        return random.sample(all_cookies, 1)[0]


if __name__ == '__main__':
    username = cp.get('baidu', 'USERNAME')
    password = cp.get('baidu', 'PASSWORD')
    cookies_list = login(username, password)
    cookies = json.dumps(cookies_list)
    print("获取Cookies成功!")
    with open('cookies/baidu_cookies.txt', 'a', encoding="utf-8") as f:
        f.write(cookies)
